import 'dart:convert';

import 'package:example_example/global/Global.dart';
import 'package:example_example/global/GlobalUrl.dart';
import 'package:example_example/pages/view/HeaderView.dart';
import 'package:example_example/util/HttpUtil.dart';
import 'package:example_example/util/LogUtil.dart';
import 'package:example_example/util/Storage.dart';
import 'package:example_example/util/ToastUtils.dart';
import 'package:flutter/material.dart';

import '../../YColors.dart';
import '../../services/TLSizeFit.dart';
import '../../bean/BossBean.dart';
import '../Tabs.dart';
import 'Login.dart';

class ChangeCodePage extends StatefulWidget {
  Map arguments;

  ChangeCodePage({Key key, this.arguments}) : super(key: key);

//  ChangeCodePage({Key key}) : super(key: key);

  _ChangeCodePageState createState() => _ChangeCodePageState();
}

class _ChangeCodePageState extends State<ChangeCodePage> {
  String primaryCode = "";
  String newCode = "";
  String confirmCode = "";

  /*
   * 密码中删除的图标显示的标记
   */
  bool flagCodeDeleteImg_primary = false;
  bool flagCodeDeleteImg_new = false;
  bool flagCodeDeleteImg_confirm = false;

  /*
   * 密码中是否隐藏输入密码显示的标记
   */
  bool flagSeeImg_primary = true;
  bool flagSeeImg_new = true;
  bool flagSeeImg_confirm = true;

  var flag;
  var CHANGECODESTATE;

  TextEditingController _controller_code_primary = new TextEditingController();
  TextEditingController _controller_code_new = new TextEditingController();
  TextEditingController _controller_code_confirm = new TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    flag = widget.arguments[Global.FLAG];
    CHANGECODESTATE = widget.arguments[Global.CHANGECODESTATE];
    if (flag == null) {
      flag = '';
    }
    if (CHANGECODESTATE == null) {
      CHANGECODESTATE = '';
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: HeaderView(
        title: "修改密码",
        isShowReturnArrow: true,
        actionList: [
//          Center(
//            child: InkWell(
//              child: Text("提交"),
//              onTap: () {
//                changeHttp();
//              },
//            ),
//          ),
          TextButton(
              onPressed: () {
//                changeHttp();
                _loginOutDialog();
              },
              child:
                  Text("退出登录", style: TextStyle(color: YColors.t, fontSize: 14)))
        ],
      ),
      body: Container(
        color: YColors.orderBackground,
        padding: EdgeInsets.only(top: TLSizeFit.setPx(10)),
//        margin: EdgeInsets.fromLTRB(
//            TLSizeFit.setPx(26), TLSizeFit.setPx(20), TLSizeFit.setPx(20), 0),
        child: setBodyView(),
      ),
    );
  }

  /**
   * 修改密码的提交
   */
  changeHttp() async {
    print("去修改密码吧");
//    密码规则: 包含大写小写字母、包含数字、包含特殊字符、长度在8~20之间
//    var pattern = RegExp(r"(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$");
//    var pattern = RegExp(r"(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$");
//    var hasMatch = pattern.hasMatch(newCode);
//    LogUtil.v("hasMatch：$hasMatch");
//
//    RegExp regExp1 = RegExp(r"[0-9]{8,20}");
//    bool hasMatch1 = regExp1.hasMatch(newCode);
//    LogUtil.v("包含数字八位数：$hasMatch1");
//
//    RegExp pattern2 = RegExp(r"[a-z]");
//    bool hasMatch2 = pattern2.hasMatch(newCode);
//    LogUtil.v("包含小写字母：$hasMatch2");
//
//    RegExp pattern3 = RegExp(r"[A-Z]");
//    bool hasMatch3 = pattern3.hasMatch(newCode);
//    LogUtil.v("包含大写字母：$hasMatch3");
//
//    var patterna = RegExp(r"[!/^()?=.*@#$&*%$]");
//    bool hasMatch6 = patterna.hasMatch(newCode);
//    LogUtil.v("包含特殊字符：$hasMatch6");

//    if (
//    value &&
//    !/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$&*%^])[A-Za-z\d!@#$&*%^]{8,20}/.test(value)
//    )

    //点击空白关闭软键盘 不关闭软键盘，toast不显示
    FocusScope.of(context).requestFocus(FocusNode());

    if (primaryCode == "") {
      ToastUtils.toast("请输入原密码");
      return;
    }
    if (newCode.length <= 0) {
      ToastUtils.toast("请输入新密码");
      return;
    }
    if (confirmCode.length <= 0) {
      ToastUtils.toast("请输入确认密码");
      return;
    }
    if (primaryCode == newCode) {
      ToastUtils.toast("新密码不能与旧密码一致");
      return;
    }
    if (confirmCode != newCode) {
      ToastUtils.toast("两次输入的密码不一致");
      return;
    }

    if (newCode.endsWith("Szgd@888888")) {
      ToastUtils.toast("为了您的账户安全，密码不能修改为初始密码");
      return;
    }

//    https://jiangdg.blog.csdn.net/article/details/110505355
    RegExp regExp = RegExp(
        r"(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$&*%^])[A-Za-z\d!@#$&*%^]{8,20}");
    bool match = regExp.hasMatch(newCode);
    LogUtil.v("正则表达式：$match");
    if (!match) {
      ToastUtils.toast("密码包含大写小写字母、数字、特殊字符、长度在8~20之间");
      return;
    }

    String url = GlobalUrl.UPDATEPWDFORLOGIN;

//    var strStor = await Storage.getString(Global.LOGINDATA);
//    var logBean = json.decode(strStor); // Json 字符串转化成 Map 类型
//    var id = logBean["id"];
//    print("获取到的id$id");

    var id = await Storage.getId(); //注意必须要用 await来修饰

    var map = {
      "originalPwd": primaryCode,
      "password": newCode,
      "password2": confirmCode,
      "id": id,
    };

    String access_token = await Storage.getToken();
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.post(url, data: map, headers: mapHeaders, success: (data) {
      print("修改密码data:$data");
//        String str =  json.encode(data);
//        print("修改密码str:$str");

      var bean = BossBean.fromJson(data);
      var success = bean.success;
      var msg = bean.msg;
      if (success) {
//        Navigator.pop(context);
        if (flag != null && flag == "force") {
          //跳转并关闭当前页面
//          Navigator.pop(context);
//          Navigator.pushNamed(
//              context, "/LoginPage");
          //跳转并关闭当前页面
          Storage.clear(); // 清除数据
          Navigator.pushAndRemoveUntil(
            context,
            new MaterialPageRoute(builder: (context) => new LoginPage()),
            (route) => route == null,
          );
        } else {
          Navigator.pop(context);
        }
      }
      ToastUtils.toast(msg);

//      修改密码data:{code: 400, success: false, data: null, msg: 密码强度不符合要求}
//          {"code":"200","success":true,"data":null,"msg":"操作成功"}
    }, error: (errorMsg) {
      print("修改密码errorMsg:$errorMsg");
    });
  }

  Widget setBodyView() {
    return Column(
      children: <Widget>[
        flag == 'force' ? tipsOne() : Container(),
        flag == 'force' ? tipsTwo() : Container(),
        Container(
          color: YColors.orderBackground,
          margin: EdgeInsets.fromLTRB(
              TLSizeFit.setPx(26), TLSizeFit.setPx(10), TLSizeFit.setPx(20), 0),
          child: setCodeView(),
        ),
      ],
    );
  }

  Widget setCodeView() {
    return Column(children: <Widget>[
      itemRowPrimary(),
      /**
       * 线
       * */
      Container(
        margin: EdgeInsets.only(top: 0),
        decoration: BoxDecoration(
            border: Border(top: BorderSide(color: YColors.l, width: 0.3)),
            color: YColors.d),
      ),
      itemRowNew(),
      Container(
        margin: EdgeInsets.only(top: 0),
        decoration: BoxDecoration(
            border: Border(top: BorderSide(color: YColors.l, width: 0.3)),
            color: YColors.d),
      ),
      itemRowConfirm(),
      signOut(),
    ]);
  }

  Widget tipsOne() {
    return Container(
      color: Color(0xffF5F5F5),
      padding: EdgeInsets.fromLTRB(TLSizeFit.setPx(20), TLSizeFit.setPx(5),
          TLSizeFit.setPx(20), TLSizeFit.setPx(5)),
      child: Text(
        CHANGECODESTATE == '21'
            ? "为了您的账户安全，请您修改初始密码，再进行下一步的操作"
            : "您的密码已到期，定期修改密码可以让您的账户更安全",
        style: TextStyle(fontSize: 14, color: Color(0xffa0a0bb)),
      ),
    );
  }

  Widget tipsTwo() {
    return Container(
      color: Color(0xffFdf6ec),
      margin: EdgeInsets.only(top: TLSizeFit.setPx(10)),
      padding: EdgeInsets.fromLTRB(TLSizeFit.setPx(20), TLSizeFit.setPx(12),
          TLSizeFit.setPx(20), TLSizeFit.setPx(12)),
      child: Text(
        "密码规则:包含大写小写字母、包含数字、包含特殊字符、长度在8-20之间",
        style: TextStyle(fontSize: 14, color: Color(0xffFFD700)),
      ),
    );
  }

  Widget signOut() {
    return InkWell(
      child: Container(
        margin: EdgeInsets.only(top: TLSizeFit.setPx(40)),
        width: TLSizeFit.setPx(100),
        height: TLSizeFit.setPx(40),
        alignment: Alignment.center,
//      decoration: BoxDecoration(
//          border: Border(
//              top: BorderSide(
//                  color: YColors.l, width: 0.3)), //dividerGreenColor
//          color: Colors.blue),
        decoration: BoxDecoration(
          color: YColors.l,
          borderRadius: BorderRadius.all(new Radius.circular(4)),
        ),
        child: Text(
          "提交",
          style: TextStyle(fontSize: 14, color: Colors.white),
        ),
      ),
      onTap: () {
//        _loginOutDialog();
        changeHttp();
      },
    );
  }
  _loginOutDialog() {
    showDialog(
        barrierDismissible: false, // 表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("您确定要退出吗？"),
            actions: <Widget>[
              FlatButton(
                  onPressed: () {
//                    logoutHttp();
                    httpJPushRegistrationID();
                  },
                  child: Text("确认")),
              FlatButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text("取消"))
            ],
          );
        });
  }

  /**
   * 给后台提交极光的注册id
   */
  httpJPushRegistrationID() async {

    String registId  = await Storage.getString(Global.JPUSHREGISTERID);

    String url = GlobalUrl.JPUSHUPDATEBINDSTATUS;
    var map = {
      "registrationId": registId,
      "validFlag": "0", //1 登录 0 退出
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.post(url,
        context: this.context,
        data: map,
        headers: mapHeaders,
        success: (data) {
          LogUtil.v("极光的注册success:$data");
//          极光的注册success:{code: 200, success: true, data: null, msg: 操作成功}
          var jsonMap = BossBean.fromJson(data);
          String result = jsonMap.code;
          String message = jsonMap.msg;
          bool success = jsonMap.success;
          if(success){
            Storage.setString(Global.JPUSHREGISTERSTATE, "");
            logoutHttp();
          }else{
            ToastUtils.toast(message);
          }
        },
        error: (error) {
          LogUtil.v("极光的注册error:$error");
        });
  }

  /**
   * 退出登录
   */
  logoutHttp() async {
    String url = GlobalUrl.LOGOUTURL;
    var map = {"": ""};
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.delete(url, data: map, headers: mapHeaders, success: (data) {
      print("退出了登录了");
//          接口的数据：{code: 200, success: true, data: null, msg: 注销成功}
      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
      if (success == true) {

//        JPush jpush = new JPush();
//        jpush.deleteAlias();  // 删除别名
        Storage.clear(); // 清除数据
        //跳转并关闭当前页面
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new LoginPage()),
              (route) => route == null,
        );
      }
      ToastUtils.toast(message);
    }, error: (errorMsg) {});
  }

  /**
   * 原密码
   */
  Widget itemRowPrimary() {
    return Row(
      children: <Widget>[
        Text(
          "原密码",
          style: TextStyle(color: YColors.b),
        ),
        SizedBox(
          width: TLSizeFit.setPx(30),
        ),
        Expanded(
          child: TextField(
            obscureText: flagSeeImg_primary,
            controller: _controller_code_primary,
            style: TextStyle(
              fontSize: 16,
              color: YColors.b,
            ),
            onChanged: (value) {
              if (value.length > 0) {
                primaryCode = value;
                setState(() {
                  flagCodeDeleteImg_primary = true;
                });
              }
            },
            decoration: InputDecoration(
              hintText: "请输入原密码",
              hintStyle: TextStyle(fontSize: 14, color: YColors.textColorHint),
              border: InputBorder.none,
            ),
          ),
        ),
        /**
         * 删除的按钮图标
         * */
        flagCodeDeleteImg_primary
            ? InkWell(
                child: Container(
                  margin: EdgeInsets.only(right: TLSizeFit.setPx(16)),
                  child: Image.asset(
                    "images/cancel_order.png",
                    width: TLSizeFit.setPx(16),
                    height: TLSizeFit.setPx(16),
                  ),
                ),
                onTap: () {
                  _controller_code_primary.clear();
                  primaryCode = "";
                  setState(() {
                    flagCodeDeleteImg_primary = false;
                  });
                },
              )
            : Container(),

        /**
         * 密码是否显示的按钮图标
         * */
        InkWell(
          child: Container(
            margin: EdgeInsets.only(right: TLSizeFit.setPx(8)),
            child: flagSeeImg_primary
                ? Image.asset(
                    "images/ic_password_normal.png",
                    width: TLSizeFit.setPx(24),
                    height: TLSizeFit.setPx(24),
                  ) //ic_password_show
                : Image.asset(
                    "images/ic_password_show.png",
                    width: TLSizeFit.setPx(24),
                    height: TLSizeFit.setPx(24),
                  ),
          ),
          onTap: () {
            setState(() {
              flagSeeImg_primary = !flagSeeImg_primary;
            });
          },
        ),
      ],
    );
  }

  /**
   * 新密码
   */
  Widget itemRowNew() {
    return Row(
      children: <Widget>[
        Text(
          "新密码",
          style: TextStyle(color: YColors.b),
        ),
        SizedBox(
          width: TLSizeFit.setPx(30),
        ),
        Expanded(
          child: TextField(
            obscureText: flagSeeImg_new,
            controller: _controller_code_new,
            style: TextStyle(
              fontSize: 16,
              color: YColors.b,
            ),
            onChanged: (value) {
              if (value.length > 0) {
                newCode = value;
                setState(() {
                  flagCodeDeleteImg_new = true;
                });
              }
            },
            decoration: InputDecoration(
              hintText: "请输入新密码",
              hintStyle: TextStyle(fontSize: 14, color: YColors.textColorHint),
              border: InputBorder.none,
            ),
          ),
        ),
        /**
         * 删除的按钮图标
         * */
        flagCodeDeleteImg_new
            ? InkWell(
                child: Container(
                  margin: EdgeInsets.only(right: TLSizeFit.setPx(16)),
                  child: Image.asset(
                    "images/cancel_order.png",
                    width: TLSizeFit.setPx(16),
                    height: TLSizeFit.setPx(16),
                  ),
                ),
                onTap: () {
                  _controller_code_new.clear();
                  newCode = "";
                  setState(() {
                    flagCodeDeleteImg_new = false;
                  });
                },
              )
            : Container(),

        /**
         * 密码是否显示的按钮图标
         * */
        InkWell(
          child: Container(
            margin: EdgeInsets.only(right: TLSizeFit.setPx(8)),
            child: flagSeeImg_new
                ? Image.asset(
                    "images/ic_password_normal.png",
                    width: TLSizeFit.setPx(24),
                    height: TLSizeFit.setPx(24),
                  ) //ic_password_show
                : Image.asset(
                    "images/ic_password_show.png",
                    width: TLSizeFit.setPx(24),
                    height: TLSizeFit.setPx(24),
                  ),
          ),
          onTap: () {
            setState(() {
              flagSeeImg_new = !flagSeeImg_new;
            });
          },
        ),
      ],
    );
  }

  /**
   * 确认密码
   */
  Widget itemRowConfirm() {
    return Row(
      children: <Widget>[
        Text(
          "确认密码",
          style: TextStyle(color: YColors.b),
        ),
        SizedBox(
          width: TLSizeFit.setPx(20),
        ),
        Expanded(
          child: TextField(
            obscureText: flagSeeImg_confirm,
            controller: _controller_code_confirm,
            style: TextStyle(
              fontSize: 16,
              color: YColors.b,
            ),
            onChanged: (value) {
              if (value.length > 0) {
                confirmCode = value;
                setState(() {
                  flagCodeDeleteImg_confirm = true;
                });
              }
            },
            decoration: InputDecoration(
              hintText: "请输入确认密码",
              hintStyle: TextStyle(fontSize: 16, color: YColors.textColorHint),
              border: InputBorder.none,
            ),
          ),
        ),
        /**
         * 删除的按钮图标
         * */
        flagCodeDeleteImg_confirm
            ? InkWell(
                child: Container(
                  margin: EdgeInsets.only(right: TLSizeFit.setPx(16)),
                  child: Image.asset(
                    "images/cancel_order.png",
                    width: TLSizeFit.setPx(16),
                    height: TLSizeFit.setPx(16),
                  ),
                ),
                onTap: () {
                  _controller_code_confirm.clear();
                  confirmCode = "";
                  setState(() {
                    flagCodeDeleteImg_confirm = false;
                  });
                },
              )
            : Container(),

        /**
         * 密码是否显示的按钮图标
         * */
        InkWell(
          child: Container(
            margin: EdgeInsets.only(right: TLSizeFit.setPx(8)),
            child: flagSeeImg_confirm
                ? Image.asset(
                    "images/ic_password_normal.png",
                    width: TLSizeFit.setPx(24),
                    height: TLSizeFit.setPx(24),
                  ) //ic_password_show
                : Image.asset(
                    "images/ic_password_show.png",
                    width: TLSizeFit.setPx(24),
                    height: TLSizeFit.setPx(24),
                  ),
          ),
          onTap: () {
            setState(() {
              flagSeeImg_confirm = !flagSeeImg_confirm;
            });
          },
        ),
      ],
    );
  }
}
